const path = require('path');
const TerserPlugin = require('terser-webpack-plugin');
const MiniCssExtractPlugin = require('mini-css-extract-plugin');
const CssMinimizerPlugin = require('css-minimizer-webpack-plugin');

const resolve = (dir) => path.join(__dirname, dir);

module.exports = (env) => {
	return {
		mode: env.production ? 'production' : 'development',
		entry: {
			cquery: {
				import: './src/index.js',
				filename: 'cquery.js',
			},
		},
		output: {
			path: path.resolve(__dirname, env.production ? 'dist/src' : 'docs/.vuepress/public/libs/cquery'),
			clean: env.production ? true : false,
			library: {
				name: 'cquery',
				type: 'umd',
			},
			globalObject: 'globalThis',
		},
		resolve: {
			alias: {
				'@': resolve('src'),
			},
		},
		plugins: [
			new MiniCssExtractPlugin({
				filename: 'cquery.css',
				chunkFilename: '[id].css',
			}),
		],
		module: {
			rules: [
				{
					test: /\.css$/i,
					use: [MiniCssExtractPlugin.loader, 'css-loader'],
				},
				{
					test: /\.s[ac]ss$/i,
					use: [
						{
							loader: MiniCssExtractPlugin.loader,
							options: {},
						},
						'css-loader',
						{
							loader: 'sass-loader',
							options: {
								additionalData: `
                  @import "./src/style/_variables.scss";
                  @import "./src/style/_mixin.scss";
                  @import "./src/style/_breakpoints.scss";
                `,
							},
						},
					],
				},
			],
		},
		optimization: {
			minimize: true,
			minimizer: [
				new TerserPlugin(), // javascript压缩
				new CssMinimizerPlugin(), // css压缩
			],
		},
	};
};
